package com.tbit.uqbike.service.business.impl;

import cn.hutool.core.lang.TypeReference;
import com.alibaba.fastjson.JSON;
import com.tbit.uqbike.constant.RedisConstant;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.*;
import com.tbit.uqbike.service.base.RedisService;
import com.tbit.uqbike.service.business.WeixinPayConfigService;
import com.tbit.uqbike.webmanager.dao.core.AdaPayConfigDao;
import com.tbit.uqbike.webmanager.dao.core.WeChatOperationConfigurationDao;
import com.tbit.uqbike.webmanager.dao.core.WeixinPayConfigDao;
import com.tbit.uqbike.webmanager.dao.core.ZfbPayConfigDao;
import com.tbit.uqbike.webmanager.dao.log.MerchantLogDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service("weixinPayConfigService")
@Slf4j
public class WeixinPayConfigServiceImpl implements WeixinPayConfigService {
    @Autowired
    private WeixinPayConfigDao weixinPayConfigDao;
    @Autowired
    private RedisService redisService;
    @Resource
    private ZfbPayConfigDao zfbPayConfigDao;
    @Resource
    private AdaPayConfigDao adaPayConfigDao;
    @Resource
    private MerchantLogDao merchantLogDao;
    @Resource
    private WeChatOperationConfigurationDao weChatOperationConfigurationDao;


    @Override
    public WeixinPayConfig getByAccountId(Integer accountId, Integer type) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("accountId", accountId);
        params.put("type", type);

        return weixinPayConfigDao.getByAccountId(params);
    }


    @Override
    public void edit(WeixinPayConfig weixinPayConfig) {
        //记录商户变更日志
        Map<String, Object> requestBody = JSON.parseObject(JSON.toJSONString(weixinPayConfig), new TypeReference<Map<String, Object>>() {
        });
        addLog(weixinPayConfig.getAccountId(), 0, weixinPayConfig.getOpId(), requestBody);

        WeixinPayConfig weixinPayConfigDB = getByAccountId(weixinPayConfig.getAccountId(), weixinPayConfig.getType());
        if (weixinPayConfigDB != null) {
            if (weixinPayConfig.getRemark() == null) {
                weixinPayConfig.setRemark(weixinPayConfigDB.getRemark());
            }
            weixinPayConfigDao.edit(weixinPayConfig);
            /**清除redis数据*/
            redisService.del(RedisConstant.WXPAY_KEY_PREFIX + weixinPayConfig.getAccountId());
        } else {
            weixinPayConfigDao.add(weixinPayConfig);
        }
    }

    @Override
    public void deleteWxConfig(Integer accountId, Integer type) {
        weixinPayConfigDao.delete(accountId, type);
        redisService.del(RedisConstant.WXPAY_KEY_PREFIX + accountId);
    }

    /**
     * 商户变更日志
     * @param accountId 品牌id
     * @param type 0:微信 1:支付宝 2:汇付
     * @param opId 操作人id
     */
    public void addLog(Integer accountId, Integer type, Integer opId, Map<String, Object> requestBody){
        try {
            if (Objects.isNull(accountId)) {
                throw new BaseException("请选择品牌");
            }
            //根据类型查询旧商户数据转成JSON
            String oldMerchant = "";
            String newMerchant = JSON.toJSONString(requestBody);
            switch (type) {
                case 0:
                    WeixinPayConfig weixinPayConfig = weixinPayConfigDao.getByAccountId(requestBody);
                    if (Objects.nonNull(weixinPayConfig)) {
                        oldMerchant = JSON.toJSONString(weixinPayConfig);
                    }
                    break;
                case 1:
                    ZfbPayConfig zfbPayConfig = zfbPayConfigDao.getByAccountId(Integer.parseInt(requestBody.get("accountId").toString()), Integer.parseInt(requestBody.get("type").toString()));
                    if (Objects.nonNull(zfbPayConfig)) {
                        oldMerchant = JSON.toJSONString(zfbPayConfig);
                    }
                    break;
                case 2:
                    AdaPayConfig adaPayConfig = new AdaPayConfig();
                    adaPayConfig.setAccountId(Integer.parseInt(requestBody.get("accountId").toString()));
                    adaPayConfig.setConfigType(Integer.parseInt(requestBody.get("configType").toString()));
                    AdaPayConfig infoByAccountIdNew = adaPayConfigDao.getInfoByAccountIdNew(adaPayConfig);
                    if (Objects.nonNull(infoByAccountIdNew)) {
                        oldMerchant = JSON.toJSONString(infoByAccountIdNew);
                    }
                    break;
                case 3:
                    WeChatOperationConfiguration wechat = weChatOperationConfigurationDao.selectByBrandId(Integer.parseInt(requestBody.get("accountId").toString()));
                    if (Objects.nonNull(wechat)) {
                        oldMerchant = JSON.toJSONString(wechat);
                    }
                    break;

                default:
                    log.info("类型解析异常:{}", type);
            }
            MerchantLog merchantLog = new MerchantLog();
            merchantLog.setBrandId(accountId)
                    .setMerchantType(type)
                    .setBeforeParameters(oldMerchant)
                    .setAfterParameters(newMerchant)
                    .setUpdateTime(new Date())
                    .setOpId(opId);
            //免押免密设置为null
            if (3 == type){
                merchantLog.setType(null);
            }else {
               merchantLog.setType(type == 2 ? Integer.parseInt(requestBody.get("configType").toString()) : Integer.parseInt(requestBody.get("type").toString()));
            }
            merchantLogDao.insert(merchantLog);
        } catch (Exception e) {
            log.error("新增商户变更日志失败", e);
        }
    }

    @Override
    public void removeCache(Integer accountId, Integer type) {
        redisService.del(RedisConstant.WXPAY_KEY_PREFIX + accountId + "." + type);
    }
}